import { useState, useEffect } from "react";
import { create } from "zustand";
import { persist, devtools, subscribeWithSelector } from "zustand/middleware";
// import { create } from "./myzustand";
import "./App.css";

// 中间件
function middleware(func) {
  return function (set, get, store) {
    function newSet(...args) {
      console.log("中间件1", get());
      return set(...args);
    }
    return func(newSet, get, store);
  };
}

// persist 就是同步 store 数据到 localStorage 的。
// const useXxxStore = create(
//   persist(
//     (set) => ({
//       aaa: "",
//       bbb: "",
//       updateAaa: (value) => set({ aaa: value }),
//       updateBbb: (value) => set({ bbb: value }),
//     }),
//     {
//       name: "xxx",
//     }
//   )
// );

const useXxxStore = create(
  subscribeWithSelector((set) => ({
    aaa: "aaaa",
    bbb: "",
    updateAaa: (value) => {
      console.log("Updating aaa to:", value); // 添加日志
      set({ aaa: value });
    },
    updateBbb: (value) => set({ bbb: value }),
  }))
);
function App() {
  const updateAaa = useXxxStore((state) => state.updateAaa);
  const aaa = useXxxStore((state) => state.aaa);

  return (
    <>
      <div>
        <input value={aaa} onChange={(e) => updateAaa(e.target.value)} />
        <Bbb></Bbb>
      </div>
    </>
  );
}

export default App;

function Bbb() {
  return (
    <>
      <div>
        <Ccc></Ccc>
      </div>
    </>
  );
}
function Ccc() {
  const aaa = useXxxStore((state) => state.aaa);
  useEffect(() => {
    // 订阅 aaa 的变化
    // const unsubscribe = useXxxStore.subscribe((newAaa, prevAaa) => {
    //   console.log("aaa变化了", prevAaa.aaa, "->", newAaa); // 添加详细日志
    // });
    // 正确使用 subscribe 监听 aaa 变化
    // 使用中间件的写法
    const unsubscribe = useXxxStore.subscribe(
      (state) => state.aaa,
      (newAaa, prevAaa) => {
        console.log("aaa变化了:", prevAaa, "->", newAaa);
      },
      {
        fireImmediately: true, // 立即触发一次回调
      }
    );
    console.log("useXxxStore", useXxxStore);

    return () => {
      unsubscribe();
    };
  }, []); // 空依赖数组确保只在组件挂载和卸载时执行
  return <p>hello,{aaa}</p>;
}
